﻿using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

using SunXNA.RainbowXNA.Batch;

namespace SunXNA.RainbowXNA.RenderObject
{
    class CModelMeshPartRenderObject : IBaseRenderObject
    {
        #region Public Types
        #endregion

        #region Private Member Variables

        private ModelMesh m_mesh;
        private ModelMeshPart m_meshPart;

        #endregion

        #region Public Accessors

        public BoundingSphere Volume
        {
            get
            {
                return m_mesh.BoundingSphere;
            }
        }

        public BoundingBox Box
        {
            get
            {
                return BoundingBox.CreateFromSphere(m_mesh.BoundingSphere);
            }
        }

        public ModelMesh Mesh
        {
            get
            {
                return m_mesh;
            }
        }

        #endregion

        #region Public Member Functions

        public CModelMeshPartRenderObject(ModelMesh mesh, ModelMeshPart meshPart)
        {
            m_mesh = mesh;
            m_meshPart = meshPart;
        }

        public void Draw(GraphicsDevice device, Matrix m4World, Matrix m4View, Matrix m4Projection)
        {
            device.Vertices[0].SetSource(m_mesh.VertexBuffer, m_meshPart.StreamOffset, m_meshPart.VertexStride);

            device.VertexDeclaration = m_meshPart.VertexDeclaration;

            device.Indices = m_mesh.IndexBuffer;

            device.DrawIndexedPrimitives(PrimitiveType.TriangleList,
                                         m_meshPart.BaseVertex,
                                         0,
                                         m_meshPart.NumVertices,
                                         m_meshPart.StartIndex,
                                         m_meshPart.PrimitiveCount);
        }

        public void AddToBatch(CBatchManager batchManager, CRainbowXNA.CRenderInstance instance)
        {
            batchManager.Add(instance);
        }

        public CRainbowXNA.CRenderInstance CreateDefaultInstance(CRainbowXNA.RenderObjectHandleType handle, CRainbowXNA rainbow)
        {
            Trace.Assert(handle.RenderObject == this);
            return new CRainbowXNA.CRenderInstance(handle);
        }

        #endregion
    }
}
